﻿using System;
using System.IO;

using Microsoft.WowAddonStudio.Lua.Adapters;
using Microsoft.WowAddonStudio.Lua.AST;
using Microsoft.WowAddonStudio.Lua.Model;

namespace Microsoft.WowAddonStudio.Lua.Parser
{
    /// <summary>
    /// A <see cref="Parser"/> that provides documentation of the declarations of the lexical scopes.
    /// </summary>
    public class DocumentationParser : ScopedParser<DocumentationScope>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="DocumentationParser"/> class.
        /// </summary>
        public DocumentationParser()
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="DocumentationParser"/> class.
        /// </summary>
        /// <param name="globalScope">The global scope.</param>
        public DocumentationParser(DocumentationScope globalScope) : base(globalScope)
        {
        }

        /// <summary>
        /// Parses the source.
        /// </summary>
        /// <returns>True, if the parse was successful; False otherwise.</returns>
        public override bool Parse()
        {
            bool success = base.Parse();
            if (success)
                this.AddDocumentation();
            return success;
        }

        private void AddDocumentation()
        {
            DocumentationAdapter<Chunk>.AddDocumentation(this.Chunk);
        }

        public new static DocumentationScope Parse(Stream stream)
        {
            if (stream == null)
                throw new ArgumentNullException("stream");

            // Create a parser
            var parser = Parser.CreateParser<DocumentationParser>(stream);

            // Parse the source
            parser.Parse();

            // Return the parser scope
            return parser.Scope;
        }

        public new static DocumentationScope Parse(string source)
        {
            if (source == null)
                throw new ArgumentNullException("source");

            // Create a parser
            var parser = Parser.CreateParser<DocumentationParser>(source);

            // Parse the source
            parser.Parse();

            // Return the global scope
            return parser.Scope;
        }
    }
}
